// pages/template/share.js
import Router from '../../../utils/router.js'
import authorize from '../../../utils/authorize'
import util from '../../../utils/util.js'
import base from '../../../config/base.js';
//canvas 绘制 图配置信息
import fb from '../../../utils/hbshare.js'
const canvasWH = fb.canvasWH;
const shareJSON = fb.shareJSON;
var idx = -1,
  erweimaInfo = null;//绘制图片下标
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    share: {
      type: Object,
      value: {
        isShow: false,
        animate: false,
        bybsid: ''
      }
    },
    paymask: {
      type: Object,
      value: {}
    },
    user_info: {
      type: Object
    },
    activity: {
      type: Object
    },
    headimgtempFilePath: {
      type: String
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    imagePath: [],
    flag: false,
    swiper:{
      indicatorDots: false,
      autoplay: false,
      interval: 1000,
      current: 0
    }
  },

  ready(){
    let v = null;
    try {
      v = util.compareVersion('2.0.7');
    }catch(e){
      console.log(e);
    }

    let properties = this.properties;
    this.setData({
      v,
      user_info: properties.user_info,
      activity: properties.activity,
      headimgtempFilePath: properties.headimgtempFilePath
      // user_info: wx.getStorageSync('user_info'),
      // activity: wx.getStorageSync('activity')
    });
    let name = 'scope.writePhotosAlbum'
    wx.getSetting({
      success: (res) => {
        let authsave = '';
        let arrAuthSetting = Object.getOwnPropertyNames(res.authSetting);
        // 提示过用户授权 但是没有通过
        if (arrAuthSetting.indexOf(name) > -1) {
          if (res.authSetting[name]) {
            authsave = 1;
          } else {
            if (v != -1) {
              authsave = 0;
            } else {
              authorize('writePhotosAlbum');
            }
          }
        } else {
          authsave = -1;
        }
        this.setData({
          authsave
        });
      }
    });
    idx = -1;
  },
  detached(){
    idx = -1;
    erweimaInfo = null;
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 阻止冒泡事件
     */
    catchtap: function () { },
    /**
     * 取消弹框
     */
    hidemask: function () {
      var that = this,
        share = that.data.share,
        time = 200;
      share.isShow = true;
      share.animate = false;
      that.setData({
        share: share
      });
      setTimeout(function () {
        share.isShow = false;
        that.setData({
          share: share
        });
      }, time);
    },
    opensetting(e){
      let authsave = 0;
      if (e.detail.authSetting && e.detail.authSetting['scope.writePhotosAlbum']) {
        authsave = 1;
        // this.downIMG();
      } else {
        authsave = 0;
      }
      this.setData({
        authsave
      });
    },
    swiperTimeout: null,
    changeswiper(e){
      let changecurrent = e.detail.current,
        current = 'swiper.current'
      if (this.swiperTimeout) { clearTimeout(this.swiperTimeout) }
      this.swiperTimeout = setTimeout(()=>{
        this.setData({
          [current]: changecurrent
        });
      }, 200);
    },
    changeswi(e){
      if(!this.data.clickflagswiper){
        let typ = e.currentTarget.dataset.type,
          current = this.data.swiper.current,
          length = this.data.imagePath.length;
        if (typ=='prev'){
          if (current>0){
            current--;
          }
        }else if(typ=='next'){
          if (current<length-1){
            current++;
          }
        }
        this.setData({
          ['swiper.current']: current,
          clickflagswiper: true
        });
        setTimeout(()=>{
          this.setData({
            clickflagswiper: false
          });
        }, 800);
      }
    },
    showCard() {//分享盆友圏 出卡片
      var _this = this;
      if(_this.data.flag){
        return;
      }
      _this.data.flag = true;
      //直接生成图片
      wx.showLoading({
        title: '图片生成中',
      })
      _this.createNewImg();
      return ;
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: "ease",
        delay: 0
      })
      _this.frendanimate = animation
      animation.translateY(500).step()
      _this.setData({
        frendanimate: animation.export(),
        showcard: true
      })
      setTimeout(function () {
        animation.translateY(0).step()
        _this.setData({
          frendanimate: animation.export()
        })
        wx.showLoading({
          title: '图片生成中',
        })
        _this.createNewImg();
      }.bind(_this), 100)
    },
    createNewImg() {//开始画图
      idx++;
      var _this = this;
      if (idx < shareJSON.length && this.data.imagePath.length < shareJSON.length){
        var context = wx.createCanvasContext('mycanvas', 'this');
        //清除  画布 内容
        // context.clearRect(0, 0, canvasWH.w, canvasWH.h);
        this.setWxbg(context)
      }else{
        wx.hideLoading();
        _this.downImage();
      }
    },
    setWxbg(context) {
      let _this = this,
        bgImg = shareJSON[idx].bgImg;
      try {
        var path = bgImg.url;
        wx.downloadFile({
          url: path,
          success(res) {
            if(res.statusCode==200){
              context.drawImage(res.tempFilePath, bgImg.x, bgImg.y, bgImg.w, bgImg.h);
            } else {
              _this.errorDraw('第'+idx+'个背景图绘制失败');
            }
            _this.setWxtx(context)
            // _this.setWxma(context)
          }, fail(res) {
            _this.errorDraw();
          }
        })
      } catch (err) {
        console.log('setWxbg', err);
        _this.errorDraw();
      }
    },
    setWxma(context) {
      let _this = this,
        ewmImg = shareJSON[idx].ewmImg;
      try {
        if (erweimaInfo){
          context.drawImage(erweimaInfo, ewmImg.x, ewmImg.y, ewmImg.w, ewmImg.h);
          _this.setWxtx(context);
        }else {
          let user_info = _this.data.user_info,
            auth_token = wx.getStorageSync('auth_token'),
            path = encodeURIComponent(`pages/store/index?bybsid=${_this.data.share.bybsid}&customer_id=${user_info.id}&store_id=${wx.getStorageSync('bslnid')}`),
            url = base.apiUrl + '/getCustomerQrCode?' + '&path=' + path + '&scene=1012' + '&auth_token=' + auth_token;
          wx.downloadFile({
            url: url,
            success(res) {
              if (res.statusCode == 200) {
                erweimaInfo = res.tempFilePath;
                
                _this.circleImg(context, res.tempFilePath, ewmImg.x, ewmImg.y, ewmImg.w, ewmImg.h);
                // context.drawImage(res.tempFilePath, ewmImg.x, ewmImg.y, ewmImg.w, ewmImg.h);
                _this.last(context);
              }
              else if (res.statusCode == 401) {
                _this.errorDraw('登录过期');
                setTimeout(()=>{
                  const currentPages = getCurrentPages();
                  const fromPageUrl = '/' + currentPages[currentPages.length - 1].__route__ || '';
                  Router.go('register', `to=${encodeURIComponent(fromPageUrl)}`);
                }, 500)
              }
              else {
                _this.errorDraw('第' + idx + '个小程序码绘制失败');
              }
              _this.setWxtx(context);
            }, fail(res) {
              _this.errorDraw();
            }
          })
        }
      } catch (err) {
        console.log('setWxma', err);
        _this.errorDraw();
      }
    },
    setWxtxBg(context) {
      let _this = this,
        txImgbg = shareJSON[idx].txImgbg;
      try {
        var path = txImgbg.url;
        wx.downloadFile({
          url: path,
          success(res) {
            if (res.statusCode == 200) {
              context.drawImage(res.tempFilePath, txImgbg.x, txImgbg.y, txImgbg.w, txImgbg.h);
            } else {
              _this.errorDraw('第' + idx + '个背景图绘制失败');
            }
            _this.setWxtext(context);
          }, fail(res) {
            _this.errorDraw();
          }
        })
      } catch (err) {
        console.log('setWxbg', err);
        _this.errorDraw();
      }
    },
    setWxtx(context) {
      let _this = this,
        txImg = shareJSON[idx].txImg;
      try{
        wx.downloadFile({
          url: _this.data.user_info.avatar,
          success(res) {
            if(res.statusCode==200){
              context.drawImage(res.tempFilePath, txImg.x, txImg.y, txImg.w, txImg.h);
            } else {
              _this.errorDraw('第'+idx+'个微信头像绘制失败');
            }
            _this.setWxtxBg(context)
          }, fail(res) {
            context.drawImage(_this.data.headimgtempFilePath, txImg.x, txImg.y, txImg.w, txImg.h);
            _this.setWxtxBg(context)
            // _this.errorDraw();
          }
        })
      }catch(err) {
        console.log('setWxtx', err);
        _this.errorDraw();
      }
    },
    circleImg(context, img, x, y, r) { //切圆方法
      let _this = this;
      try{
        context.save();
        context.beginPath();
        r = r / 2;//半径
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        context.arc(cx, cy, r, 0, 2 * Math.PI);
        context.clip();
        context.drawImage(img, x, y, d, d);
        context.restore();
        // this.setWxtext(context);
      }catch(err) {
        console.log('circleImg', err);
        _this.errorDraw();
      }
    },
    setWxtext(context) {
      let _this = this,
        invite_me = shareJSON[idx].invite_me,
        invite_code = shareJSON[idx].invite_code,
        invite_code_txt = shareJSON[idx].invite_code_txt,
        invite_xy_txtfn = shareJSON[idx].invite_xy_txtfn(),
        invite_xy_txt1 = shareJSON[idx].invite_xy_txt1,
        invite_xy_txt2 = shareJSON[idx].invite_xy_txt2;
      try{
        invite_me.txt = _this.data.user_info.user_nickname;
        let aa = _this.setWxtextfn(context, invite_me, 2);//2 算出每个字宽度
        invite_code.txt = '';//`长按识别二维码`;
        _this.setWxtextfn(context, invite_code);
        invite_code_txt.txt = '';//'领取现金大礼包';
        _this.setWxtextfn(context, invite_code_txt);
        //invite_xy_txt1.txt = invite_xy_txtfn[0];
        //_this.setWxtextfn(context, invite_xy_txt1, 1);//1 居中
        //invite_xy_txt2.txt = invite_xy_txtfn[1];
        //_this.setWxtextfn(context, invite_xy_txt2, 1);//1 居中
        // _this.last(context);
        _this.setWxma(context)
      } catch (err) {
        console.log('setWxtext', err);
        _this.errorDraw();
      }
    },
    setWxtextfn(context, obj, t){
      let _this = this;
      try{
          context.setFontSize(obj.size);
          context.setFillStyle(obj.color);
          context.setTextAlign(obj.textalgin)
          if (t==1) {
            context.fillText(obj.txt, (canvasWH.w - context.measureText(obj.txt).width) / 2, obj.y);
          }else if(t==2){
            let chr = obj.txt.split(''),
              temp = '';
            let b = 0;
            for (var a = 0; a < chr.length; a++) {
              if (context.measureText(temp).width < 160) {
                b++;
                temp += chr[a];
              }else {
                context.fillText(temp + '...邀你来看红包雨', obj.x, obj.y);
                break;
              }
            }
            if (b == chr.length){
              context.fillText(temp + '邀你来看红包雨', obj.x, obj.y);
            } 
          } else {
            context.fillText(obj.txt, obj.x, obj.y);
          }
          context.save();
      } catch (err) {
        console.log('setWxtext', err);
        _this.errorDraw();
      }
    },
    last(context) {
      let _this = this;
      try{
        context.draw(false, function (e) {
          wx.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function (res) {
              var imagePath = _this.data.imagePath;
              imagePath.push(res.tempFilePath);
              _this.setData({
                imagePath 
              });
              _this.createNewImg();
            }, fail(res) {
              _this.errorDraw();
            }
          })
        })
      } catch (err) {
        console.log('last', err);
        _this.errorDraw();
      }
    },
    errorDraw(str) {
      wx.hideLoading()
      wx.showToast({
        title: str || '第'+(idx+1)+'个图片生成失败，请重试！',
        icon: 'none'
      })
    },
    downImage() {//保存下载
      var _this = this;
      authorize('writePhotosAlbum', (b) => {
        if (b) {
          _this.downIMG();
        }else{
          if (_this.data.v != -1) {
            wx.showToast({
              title: '您未授权保存到相册功能，设置后正常使用',
              icon: 'none'
            })
            this.setData({
              authsave: 0
            });
          } else {
            wx.showModal({
              title: '授权提示',
              content: '您未授权保存到相册功能，设置后正常使用',
              showCancel: false,
              success: res => {
                wx.openSetting({
                  success: res => { },
                  fail: res => { }
                })
              }
            })
          }
        }
      })
    },
    downIMG(){
      let _this = this;
      wx.saveImageToPhotosAlbum({
        filePath: _this.data.imagePath[_this.data.swiper.current],
        success() {
          wx.showToast({
            title: '保存图片成功',
            icon: 'none'
          })
        }
      })
      _this.setData({
        flag: false
      })
    },
    hidecard() {//隐藏卡片
      var _this = this;
      wx.hideLoading();
      _this.setData({
        showcard: false
      })
    },
  }
})
